import React from "react";

import { Link} from 'react-router-dom';

import PageContent from '../../PageContent'

import { ajax ,showResultMessage,isNull,isNotNull,setStoreItem,getStoreItem} from '../../common';

import {UIDataTableView} from '../../uicomponents/UIDataComponentView';

import UICardTabs from '../../uicomponents/UICardTabs';

import UIFormView from '../../uicomponents/UIFormView';

import UIToolbar from '../../uicomponents/UIToolbar';

import ImportProductUIListDataPanel from './ImportUIDataFilePanel';

import ExportProductUIListPanel from './ExportUIDataFilePanel';

/** 
 * UIList管理应用入口
*/
export default class ProductUIListDataManageApp extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
			staticListSearchValues : getStoreItem('staticListSearchValues',{}),
			dynamicListSearchValues : getStoreItem('dynamicListSearchValues',{}),
        };
	}
	
	onTabChange = (tabName) => {
		//this.setState({activeTabKey : tabName});
		this.activeTabKey = tabName;
	}

	onStaticListSearchValueChange = (values) => {
		this.setState({staticListSearchValues : values});
		setStoreItem('staticListSearchValues',values);
	}

	onDynamicListSearchValueChange = (values) => {
		this.setState({dynamicListSearchValues : values});
		setStoreItem('dynamicListSearchValues',values);
	}

	shouldComponentUpdate(nextProps,nextState){
		if(nextState.staticListSearchValues == this.state.staticListSearchValues){
		  return false
		}
		else if(nextState.staticListSearchValues == this.state.staticListSearchValues){
		  return false
		}
		else{
			return true;
		}
	}

    render() {

		/**路由设置 */
		const pageContentMap = {
			'/': {
				text: '',
				icon: '',
				getComponent: (owner, props) => {
					return (<ProductUIListDataTabsPanel {...props} 
						activeTabKey={this.activeTabKey}
						staticListSearchValues={this.state.staticListSearchValues} 
						onStaticListSearchValueChange={this.onStaticListSearchValueChange}
						dynamicListSearchValues={this.state.dynamicListSearchValues} 
						onDynamicListSearchValueChange={this.onDynamicListSearchValueChange} 
						onTabChange={this.onTabChange} 
						key="UIListDataTabs" />
					);
				}
			},
			'/editUIListOptions': {
				text: '编辑关联动作',
				icon: 'edit',
				getComponent: (owner, props) => {
					return (<EditProductUIListOptionsPanel {...props} key="editUIListOptions" />);
				}
			},
			'/importDataFiles': {
				text: '导入UI列表',
				icon: 'sign-in-alt',
                getComponent: (owner, props) => {
                    return <ImportProductUIListDataPanel {...props} importURL="PRODUCT/UI/import/importUIListDataFile/" pageTitle="导入UI列表" key="importListDatas"/>;
                }
			},
			'/exportDataFiles': {
				text: '导出UI列表',
				icon: 'sign-out-alt',
                getComponent: (owner, props) => {
                    return <ExportProductUIListPanel {...props} exportURL="PRODUCT/UI/export/exportUIListFile/" pageTitle="导出UI列表" key="exportLists"/>;
                }
			},
		};

        return (
            <PageContent pageInstance={this} contentMap={pageContentMap} {...this.props}>

            </PageContent>
        );
    }
};

/** 
 *产品UI列表管理
*/
class ProductUIListDataTabsPanel extends React.Component {

    onTabChange = (tabName) => {
        switch (tabName) {
            case 'staticListInfo':
                this.staticListRef.loadList();
                break;
            case 'dynamicListInfo':
                this.dynamicListRef.loadList();
                break;
		}
		if(this.props.onTabChange !== undefined){
            this.props.onTabChange(tabName);
        }
    }

	actionHandler = (actionEvent) => {

		return {
			
		}
	}

	render() {
		const pageHistory = this.props.history;
        const tabPanelContentMap = {
			
            '/ProductUIStaticListListPanel': {
                getComponent: (owner, props) => {
                    return <ProductUIStaticListListPanel {...props} searchValues={this.props.staticListSearchValues} onSearchValueChange={this.props.onStaticListSearchValueChange} pageHistory={pageHistory} ref={(inst) => this.staticListRef = inst}/>;
                }
            },
            '/ProductUIDynamicListListPanel': {
                getComponent: (owner, props) => {
                    return <ProductUIDynamicListListPanel {...props} searchValues={this.props.dynamicListSearchValues} onSearchValueChange={this.props.onDynamicListSearchValueChange} pageHistory={pageHistory} ref={(inst) => this.dynamicListRef = inst}/>;
                }
            },
        };


		return (
			<UICardTabs 
				title="UI数据列表"
				activeTabKey={this.props.activeTabKey}
                tabConfigId="uiListListTab"
                onTabChange={this.onTabChange}
                tabContentMap={tabPanelContentMap}
				extra={<UIToolbar history={pageHistory} actionGroupId="productUIDataPanelActionGroup" actionHandler={this.actionHandler}/>}
            />
		);
	}
}

/**
 * 静态列表
 */
class ProductUIStaticListListPanel extends React.Component {

    constructor(props) {
		super(props);
		this.state = {
			formTitle: '',
			searchValues : props.searchValues,
		}
    }
    
    loadList = () => {
        this.staticListRef.loadData();
    }

	actionHandler = (actionEvent) => {

		const { selectIds,  staticListRef, staticListFormRef } = this;

		return {
			refresh : () => {
				staticListRef.loadData();
			},
			addNew : () => {
				this.setState({ formTitle: '新增静态列表'});
				setTimeout(() => {
					staticListFormRef.openModal(() => {
						const initParams = getStoreItem('staticListSearchValues',{});
						if(isNotNull(initParams['domainId'])){
							staticListFormRef.setFormData({domainId : initParams['domainId']});
						}
					});
				});
			},
			doEdit : () => {
				this.setState({ formTitle: '编辑静态列表' });
				setTimeout(() => {
					staticListFormRef.openModal(() => {
						staticListFormRef.setFormData(actionEvent.params);
					});
				});
			},
			doDelete : () => {
				let selectedIds = null;

				if (actionEvent.params != null) {
					selectedIds = [actionEvent.params.id];
				}
				else {
					selectedIds = selectIds;
				}

				ajax('PRODUCT/UI/productUIList/batchDelete', { ids: selectedIds }, (data) => {
					staticListRef.loadData();
				});
			},
			doSave : () => {
				staticListFormRef.getFormData((formData) => {
					formData.type = 'static';
					ajax('PRODUCT/UI/productUIList/save', formData, (data) => {
						staticListFormRef.closeModal();
						staticListRef.loadData();
						showResultMessage({
							success: true,
							message: 'message.saveSuccess',
						});
					});
				});
			}
		};
	}

	render() {

		const tableProps = {
			bordered : false,
			history : this.props.pageHistory,
			ref: (inst) => { this.staticListRef = inst },
			actionHandler: this.actionHandler,
			actionGroupId: 'productUIListListActionGroup',
			rowActionGroupId: 'productUIListRowActionGroup',
			tableConfigId: 'productUIStaticListTable',
			dataUrl: 'PRODUCT/UI/productUIList/query?type=static',
			selectMode: 'multi',
			searchFormId: 'productUIListSearchForm',
			initSearchValues : this.props.searchValues,
			autoLoad: true,
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('delete');
					topToolBar.enable('edit');
				}
				else {
					topToolBar.disable('delete');
					topToolBar.disable('edit');
				}
			},
			onSelectChange:
				(selectRowKeys) => {
					this.selectIds = selectRowKeys;
				}
			,
			onSearchData : (changedValues) => {
				
				if(this.props.onSearchValueChange){
					this.props.onSearchValueChange(changedValues)
				}
			}
		};

		const formProps = {
			ref: (inst) => { this.staticListFormRef = inst },
			formConfigId: 'productUIStaticListForm',
			actionGroupId: 'saveActionGroup',
			actionHandler: this.actionHandler,
			inPop: true,
			destroyOnClose: true,
			title: this.state.formTitle,
		};

		return (
			<UIDataTableView {...tableProps}>
				<UIFormView {...formProps} />
			</UIDataTableView>
		);
	}
}

/**
 * 动态列表
 */
class ProductUIDynamicListListPanel extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			formTitle: '',
			searchValues : props.searchValues,
		}
    }

    loadList = () => {
        this.listRef.loadData();
    }

    actionHandler = (actionEvent) => {

		const { selectIds, listRef, listFormRef } = this;

		return {
			refresh : () => {
				listRef.loadData();
			},
			addNew : () => {
				this.setState({ formTitle: '新增动态列表'});
				setTimeout(() => {
					listFormRef.openModal(() => {
						const initParams = getStoreItem('dynamicListSearchValues',{});
						if(isNotNull(initParams['domainId'])){
							listFormRef.setFormData({domainId : initParams['domainId']});
						}
					});
				});
			},
			doEdit : () => {
				this.setState({ formTitle: '编辑动态列表' });
				setTimeout(() => {
					listFormRef.openModal(() => {
						listFormRef.setFormData(actionEvent.params);
					});
				});
			},
			doDelete : () => {
				let selectedIds = null;

				if (actionEvent.params != null) {
					selectedIds = [actionEvent.params.id];
				}
				else {
					selectedIds = selectIds;
				}

				ajax('PRODUCT/UI/productUIList/batchDelete', { ids: selectedIds }, (data) => {
					listRef.loadData();
				});
			},
			doSave : () => {
				listFormRef.getFormData((formData) => {

					ajax('PRODUCT/UI/productUIList/save', formData, (data) => {
						listFormRef.closeModal();
						listRef.loadData();
						showResultMessage({
							success: true,
							message: 'message.saveSuccess',
						});
					});
				});
			}
		};
	}

	render() {

		const tableProps = {
			bordered : false,
			history : this.props.pageHistory,
			ref: (inst) => { this.listRef = inst },
			actionHandler: this.actionHandler,
			actionGroupId: 'productUIListListActionGroup',
			rowActionGroupId: 'productUIListRowActionGroup',
			tableConfigId: 'productUIStaticListTable',
			dataUrl: 'PRODUCT/UI/productUIList/query?type=dynamic',
			selectMode: 'multi',
			searchFormId: 'productUIListSearchForm',
			initSearchValues : this.props.searchValues,
			autoLoad: true,
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('delete');
					topToolBar.enable('edit');
				}
				else {
					topToolBar.disable('delete');
					topToolBar.disable('edit');
				}
			},
			onSelectChange:
				(selectRowKeys) => {
					this.selectIds = selectRowKeys;
				}
			,
			onSearchData : (changedValues) => {
				
				if(this.props.onSearchValueChange){
					this.props.onSearchValueChange(changedValues)
				}
			}
		};

		const formProps = {
			ref: (inst) => { this.listFormRef = inst },
			formConfigId: 'productUIDynamicListForm',
			actionGroupId: 'saveActionGroup',
			actionHandler: this.actionHandler,
			inPop: true,
			destroyOnClose: true,
			title: this.state.formTitle,
		};

		return (
			<UIDataTableView {...tableProps}>
				<UIFormView {...formProps} />
			</UIDataTableView>
		);
	}
}

/**
 * 编辑List选项
 */
class EditProductUIListOptionsPanel extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			formTitle: '',
			pageTitle : '',
		}
	}
	
	componentDidMount(){
		this.list = this.props.location.state;
		this.setState({pageTitle : '编辑[' + this.list.code +   ']选项'});
		this.loadListOptions(this.list.id);
	}

    loadListOptions = (listId) => {
		
        this.optionsListRef.loadData({listId : listId});
    }

    actionHandler = (actionEvent) => {

		const { selectIds, optionsListRef, optionFormRef,list } = this;

		return {
			refresh : () => {
				optionsListRef.loadData({listId :list.id});
			},
			addNew : () => {
				this.setState({ formTitle: '添加选项'});
				setTimeout(() => {
					optionFormRef.openModal();
				});
			},
			doEdit : () => {
				this.setState({ formTitle: '编辑动作' });
				setTimeout(() => {
					optionFormRef.openModal(() => {
						optionFormRef.setFormData(actionEvent.params);
					});
				});
			},
			doDelete : () => {
				let selectedIds = null;

				if (isNull(actionEvent.params) !== true) {
					selectedIds = [actionEvent.params.id];
				}
				else {
					selectedIds = selectIds;
				}

				ajax('PRODUCT/UI/productUIListOption/batchDelete', { ids: selectedIds }, (data) => {
					optionsListRef.loadData({listId :list.id});
				});
			},
			doSave : () => {
				optionFormRef.getFormData((formData) => {
					formData.listId = list.id;
					ajax('PRODUCT/UI/productUIListOption/save', formData, (data) => {
						optionFormRef.closeModal();
						optionsListRef.loadData({listId :list.id});
						showResultMessage({
							success: true,
							message: 'message.saveSuccess',
						});
					});
				});
			},
			moveDown : () => {
				const rowData = actionEvent.params;
				if(rowData.sortIndex < optionsListRef.getListData().length){
					rowData.sortIndex = rowData.sortIndex + 1;
					ajax('PRODUCT/UI/productUIListOption/save',rowData,(data) => {
						optionsListRef.loadData({listId :list.id});
					});
				}
			},
			moveUp : () => {
				const rowData = actionEvent.params;
				if(rowData.sortIndex > 1){
					rowData.sortIndex = rowData.sortIndex - 1;
					ajax('PRODUCT/UI/productUIListOption/save',rowData,(data) => {
						optionsListRef.loadData({listId :list.id});
					});
				}
			},
			
		};
	}

	render () {
		const tableProps = {
			bordered : false,
			title : this.state.pageTitle,
			ref: (inst) => { this.optionsListRef = inst },
			actionHandler: this.actionHandler,
			actionGroupId: 'productUIListOptionListActionGroup',
			rowActionGroupId: 'productUIListOptionRowActionGroup',
			tableConfigId: 'productUIListOptionTable',
			dataUrl: 'PRODUCT/UI/productUIListOption/query',
			selectMode: 'multi',
			autoLoad: false,
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('delete');
					topToolBar.enable('edit');
				}
				else {
					topToolBar.disable('delete');
					topToolBar.disable('edit');
				}
			},
			onSelectChange:
				(selectRowKeys) => {
					this.selectIds = selectRowKeys;
				}
			,
		};

		const formProps = {
			ref: (inst) => { this.optionFormRef = inst },
			formConfigId: 'productUIListOptionForm',
			actionGroupId: 'saveActionGroup',
			actionHandler: this.actionHandler,
			inPop: true,
			destroyOnClose: true,
			title: this.state.formTitle,
		};

		return (
			<UIDataTableView extra={<Link to="/">返回</Link>} {...tableProps}>
				<UIFormView {...formProps} />
			</UIDataTableView>
		);
	}
}